package cn.com.callback

import cn.com.elite.EliteBean
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject
import cn.com.elite.Util;

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

/**
 *
 * @Title: apiBPClosedWO
 * @Description:宝安排水系统工单数据处理同步接口--外部接口
 * @author: 匡涛
 * @date 2020-08-19 10:28:00
 *
 */

public class apiBPClosedWO implements ServiceBackInvoke {
	private static final Log log = LogFactory.getLog(apiBPClosedWO.class);

	public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

		response.setCharacterEncoding("UTF-8");

		String getMethod = request.getMethod();
		log.debug("getMethod:" + getMethod);

		String inData = "";
		String outData = "";
		String dataSourceID = "dataSource";

		BufferedReader iny = null;
		if (getMethod.equals("GET")) {
			inData = request.getParameter("data");
			log.debug("原始Get请求参数:" + inData);
		} else {
			InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
			iny = new BufferedReader(reader);
			String line;
			while ((line = iny.readLine()) != null) {
				inData += line;
			}
			log.debug("原始Post请求参数:" + inData);
		}

		try {
			// 调用处理信息
			JSONObject inObject = new JSONObject(inData);
			log.debug("处理前的Json：" + inObject.toString());

			String sys_source = GetJV(inObject, "sys_source");
			String sys_flag = GetJV(inObject, "sys_flag");
			String arr_data = GetJV(inObject, "data");

			log.debug("解析信息-sys_source：" + sys_source + " sys_flag：" + sys_flag + " arr_data：" + arr_data);

			if (sys_source == 'YYGL') {
				outData = JTHandle(eliteBean, sys_source, sys_flag, arr_data, dataSourceID);
			}

		} catch (Exception e) {
			log.error("接口处理异常" + e.getMessage());
			// 失败返回
			outData = "{\"resultcode\":\"0\",\"resultmessage\":\"处理失败(" + e.getMessage() + "),调用问题处理时长(毫秒):2\",\"data\":[]}";

		}

		log.debug("名单接入处理完成返回结果:" + outData);

		return outData;
	}

	// 排水工单处理
	public static String JTHandle(EliteBean eliteBean, String sys_source, String sys_flag, String inJson, String dataSourceID) {
		long startTime = System.currentTimeMillis();
		JSONArray arrJsonArray;
		Map<String, String> dealMap = new HashMap<String, String>();
		Map<String, String> dealMsgMap = new HashMap<String, String>();
		JSONArray resArray = new JSONArray();
		String reJson = null;
		try {
			arrJsonArray = new JSONArray(inJson);

			int arrInt = arrJsonArray.length();
			log.debug("接入List数量:" + arrInt);

			for (int i = 0; i < arrInt; i++) {

				log.debug("当前处理数组位置:" + (i + 1));
				JSONObject arrCustJson = arrJsonArray.getJSONObject(i);

				String workorderid = GetJV(arrCustJson, "workorderid");//工单唯一编号
				String handledescription = GetJV(arrCustJson, "handledescription");//处理结果
				String starttime = GetJV(arrCustJson, "starttime");//开始处理时间
				String finishtime = GetJV(arrCustJson, "finishtime");//处理完成时间
				String handlername = GetJV(arrCustJson, "handlername");//处理人名称
				String handlerphone = GetJV(arrCustJson, "handlerphone");//处理人电话
				String Arriveddate = GetJV(arrCustJson, "Arriveddate");//到达现场时间

				//申请延时步骤校验
				String dealResult = "";
				String dealMessage = "";
				if (isNull(workorderid) || isNull(handledescription) || isNull(starttime) || isNull(finishtime) || isNull(handlername)) {
					dealResult = "0";
					dealMessage = isNullMSG("workorderid", workorderid) + isNullMSG("handledescription", handledescription) + isNullMSG("starttime", starttime) + isNullMSG("finishtime", finishtime) + isNullMSG("handlername", handlername);
					log.warn("调用参数非空校验异常:" + dealMessage);
					long endTime = System.currentTimeMillis();
				} else {
					//查询现有当前工单编号是否存在现有工单
					def getSelectSQL = eliteBean.chaxun_sql("Select R1.Relation_ID, R3.Handlegroup_ID, R3.Handleby_ID, R3.CurstepStatus, R2.curstep_id_map as Curstep_Id,R1.business_source as business_source,R1.is_returnvisit as is_returnvisit,R2.objectivestatus as objectivestatus,R1.workorder_state as workorderstate From TABCCONSULTWORKORDER R1 Left Join Objective R2 On R1.Relation_Id = R2.Objective_Guid Left Join Elitetask R3 On R1.Relation_Id = R3.Objective_Guid Where R2.workorderid = '" + workorderid + "'", dataSourceID);
					log.debug("查询当前同步的工单是否已经存在 SQL:" + getSelectSQL + " 结果数量:" + getSelectSQL.size());

					//获取当前工单编号对应的CRM唯一工单Guid Relation_ID
					String old_Relation_ID = "";
					String old_Handlegroup_ID = "";
					String old_Handleby_ID = "";
					String old_CurstepStatus = "";
					String old_Curstep_Id = "";
					String business_source="";
					String is_returnvisit="";
					String objectivestatus="";
					String workorderstate="";

					if (getSelectSQL.size() > 0) {
						old_Relation_ID = getSelectSQL.get(0).get("Relation_ID");
						old_Handlegroup_ID = getSelectSQL.get(0).get("Handlegroup_ID");
						old_Handleby_ID = getSelectSQL.get(0).get("Handleby_ID");
						old_CurstepStatus = getSelectSQL.get(0).get("CurstepStatus");
						old_Curstep_Id = getSelectSQL.get(0).get("Curstep_Id");
						business_source = getSelectSQL.get(0).get("business_source");
						is_returnvisit = getSelectSQL.get(0).get("is_returnvisit");
						objectivestatus = getSelectSQL.get(0).get("objectivestatus");
						workorderstate = getSelectSQL.get(0).get("workorderstate");
					} else {
						old_Relation_ID = "";
						old_Handlegroup_ID = "";
						old_Handleby_ID = "";
						old_CurstepStatus = "";
						old_Curstep_Id = "";
						business_source="";
						is_returnvisit="";
						objectivestatus="";
						workorderstate="";
					}
					log.debug("查询现有当前工单编号是否存在现有工单-结果old_Relation_ID:" + old_Relation_ID + " old_Handlegroup_ID:" + old_Handlegroup_ID + " old_Handleby_ID:" + old_Handleby_ID + " old_CurstepStatus:" + old_CurstepStatus + " old_Curstep_Id:" + old_Curstep_Id+ " business_source:" + business_source+ " is_returnvisit:" + is_returnvisit+ " objectivestatus:" + objectivestatus+ " workorderstate:" + workorderstate+ " workorderid:" + workorderid);
					
					try {
						//此工单存在时候,处理步骤 状态打开 才能改变工单状态
						if (old_Relation_ID != null && old_Relation_ID.length() > 0&&objectivestatus=='OPEN') {
							//附件处理
							Boolean arrImg = GetJV(arrCustJson, "arrImg")
								log.debug("arrImg:	"+arrImg);
								if (arrImg==true) {
									//获取附件信息
									JSONArray arrImgJsonArray = arrCustJson.getJSONArray("arrImg");
									log.debug("arrImgJsonArray:	"+arrImgJsonArray );
									String arrImgpath = "";
									String arrImgname = "";
									if(old_Relation_ID != null || old_Relation_ID.length() > 0) {
										for (int j = 0; j < arrImgJsonArray.length(); j++) {
											JSONObject arrImgJson = arrImgJsonArray.getJSONObject(j);
											arrImgpath = GetJV(arrImgJson, "path");
											arrImgname = GetJV(arrImgJson, "name");
											def aaa=eliteBean.update("insert into rm_uploadrecord(guid,objectiveID,path,name,operator,operationtime,filedesc,type)VALUES(NEWID(),'" + old_Relation_ID + "','" + arrImgpath + "','" + arrImgname + "','运营管理系统',GETDATE(),'','4')", "dataSource");
										}
									}
								}
							
							String injson;
							def status=0;
							//将工单下送到回访节点
							if (sys_flag == "Handle"&&(business_source=='A13ACC'||business_source=='DBCA45')&&is_returnvisit=='是'&&old_Curstep_Id=='KNGZL4') {
								String[] data1 = new String[6];
								data1[0] = "insert into TABCCONSULTWORKORDER_his select NEWID(), * from TABCCONSULTWORKORDER where Relation_ID = '" + old_Relation_ID + "'"
								data1[1] = "Insert Into Workorderstep3 (Workorder_Guid, Workorderstep_Guid, Oldhandleby_Id, Oldhandlegroup_Id, Handleby_Id, Handlegroup_Id, Workorderstepstatus, Comments, Modifieddate, Workorderstepid, Stepexpired, Child_Id, Stepstart, Cur_Expiredflag, Cur_Expiredlen, From_Stepidmap, To_Stepidmap, Workstarttime, Workendtime) Values ('" + old_Relation_ID + "', NewID(), '" + old_Handleby_ID + "', '" + old_Handlegroup_ID + "', 'SELITE', 'SYSTEM', 'SENDNS', '" + handledescription + "', Getdate(), Null, Getdate(), Null, Getdate(), 0, 0, '" + old_Curstep_Id + "', 'GCH0F9', '" + starttime + "', '" + finishtime + "')";
								data1[2] = "Insert Into Workorderpath3 (Workorder_Guid, Workorderpath_Guid, Handlegroup, Handleby, Modifieddate, Fromstepid, Tostepid, Woframe_Id, Fromframeid, Handlerole_Id, From_Stepidmap, To_Stepidmap) Values ('" + old_Relation_ID + "', NewID(), 'SYSTEM', 'SELITE', Getdate(), Null, Null, 'MYI3EW', Null, Null, '" + old_Curstep_Id + "', 'GCH0F9')";
								data1[3] = "Update Objective Set Handlegroup_Id = '" + old_Handlegroup_ID + "', Handleby_Id = '" + old_Handleby_ID + "',  Curstep_Id_Map = 'GCH0F9', Modifiedby = 'SELITE', Modifieddate = Getdate(),comments='" + handledescription + "',branch_endtime=GETDATE() Where Objective_Guid = '" + old_Relation_ID + "'";
								data1[4] = "Update Elitetask Set Handlegroup_Id = '" + old_Handlegroup_ID + "', Handleby_Id = '" + old_Handleby_ID + "', Curstep_Id = 'GCH0F9', Curstep_Id_Map = 'GCH0F9', Modifiedby = 'SELITE', Modifieddate = Getdate(),comments='" + handledescription + "' Where Objective_Guid = '" + old_Relation_ID + "'";
								data1[5] = "update  TABCCONSULTWORKORDER set  r_Arriveddate='" + Arriveddate + "',r_handlername='" + handlername + "',handlerphnoe='" + handlerphone + "',r_workingday=datediff( day, '" + starttime + "', '" + finishtime + "' ),r_starttime='" + starttime + "',r_finishtime='" + finishtime + "',handledescription='" + handledescription + "',workorder_state = 4 where RELATION_ID='" + old_Relation_ID + "'";
								log.debug("判断处理工单状态进行下一步处理SQL:" + data1.toString());
								int[] dataresult1 = eliteBean.updateBatch(data1, dataSourceID);
								log.debug("判断处理工单状态进行下一步处理SQL结果:" + dataresult1.toString());
							
							//案件申请延期后，还未等延期结果下发，运管此刻推送处理结果，工单在运营管理节点结案关闭 且回退第三方（城管、网格）
							}else if(sys_flag == "Handle"&&old_Curstep_Id=='O70W2B'&&workorderstate=='3'){
								String[] data2 = new String[6];
								data2[0] = "insert into TABCCONSULTWORKORDER_his select NEWID(), * from TABCCONSULTWORKORDER where Relation_ID = '" + old_Relation_ID + "'"
								data2[1] = "Insert Into Workorderstep3 (Workorder_Guid, Workorderstep_Guid, Oldhandleby_Id, Oldhandlegroup_Id, Handleby_Id, Handlegroup_Id, Workorderstepstatus, Comments, Modifieddate, Workorderstepid, Stepexpired, Child_Id, Stepstart, Cur_Expiredflag, Cur_Expiredlen, From_Stepidmap, To_Stepidmap, Workstarttime, Workendtime) Values ('" + old_Relation_ID + "', NewID(), 'SELITE', 'SYSTEM', 'SELITE', 'SYSTEM', 'END   ', '" + handledescription + "', Getdate(), Null, Getdate(), Null, Getdate(), 0, 0, '" + old_Curstep_Id + "', 'KNGZL4', '" + starttime + "', '" + finishtime + "')";
								data2[2] = "Insert Into Workorderpath3 (Workorder_Guid, Workorderpath_Guid, Handlegroup, Handleby, Modifieddate, Fromstepid, Tostepid, Woframe_Id, Fromframeid, Handlerole_Id, From_Stepidmap, To_Stepidmap) Values ('" + old_Relation_ID + "', NewID(), 'SYSTEM', 'SELITE', Getdate(), Null, Null, 'MYI3EW', Null, Null, 'O70W2B', 'KNGZL4')";
								data2[3] = "Update Objective Set Handlegroup_Id = '" + old_Handlegroup_ID + "', Handleby_Id = '" + old_Handleby_ID + "',objectivestatus='CLOSE', Curstep_Id_Map = 'KNGZL4', Modifiedby = 'SELITE', Modifieddate = Getdate(),comments='" + handledescription + "' ,branch_endtime=GETDATE() Where Objective_Guid = '" + old_Relation_ID + "'";
								data2[4] = "delete from Elitetask  Where  Objective_Guid = '" + old_Relation_ID + "'";
								data2[5] = "update  TABCCONSULTWORKORDER set  r_Arriveddate='" + Arriveddate + "',r_handlername='" + handlername + "',handlerphnoe='" + handlerphone + "',r_workingday=datediff( day, '" + starttime + "', '" + finishtime + "' ),r_starttime='" + starttime + "',r_finishtime='" + finishtime + "',handledescription='" + handledescription + "',workorder_state = 4 where RELATION_ID='" + old_Relation_ID + "'";
								log.debug("判断处理工单状态进行下一步处理SQL:" + data2.toString());
								int[] dataresult2 = eliteBean.updateBatch(data2, dataSourceID);
								log.debug("判断处理工单状态进行下一步处理SQL结果:" + dataresult2.toString());
								
							}else{//将工单在运营管理节点结案关闭，无需回访节点
								String[] data1 = new String[5];
								data1[0] = "insert into TABCCONSULTWORKORDER_his select NEWID(), * from TABCCONSULTWORKORDER where Relation_ID = '" + old_Relation_ID + "'"
								data1[1] = "Insert Into Workorderstep3 (Workorder_Guid, Workorderstep_Guid, Oldhandleby_Id, Oldhandlegroup_Id, Handleby_Id, Handlegroup_Id, Workorderstepstatus, Comments, Modifieddate, Workorderstepid, Stepexpired, Child_Id, Stepstart, Cur_Expiredflag, Cur_Expiredlen, From_Stepidmap, To_Stepidmap, Workstarttime, Workendtime) Values ('" + old_Relation_ID + "', NewID(), '" + old_Handleby_ID + "', '" + old_Handlegroup_ID + "', 'SELITE', 'SYSTEM', 'END   ', '" + handledescription + "', Getdate(), Null, Getdate(), Null, Getdate(), 0, 0, '" + old_Curstep_Id + "', 'KNGZL4', '" + starttime + "', '" + finishtime + "')";
								data1[2] = "Update Objective Set Handlegroup_Id = '" + old_Handlegroup_ID + "', Handleby_Id = '" + old_Handleby_ID + "',objectivestatus='CLOSE', Curstep_Id_Map = 'KNGZL4', Modifiedby = 'SELITE', Modifieddate = Getdate(),comments='" + handledescription + "' ,branch_endtime=GETDATE() Where Objective_Guid = '" + old_Relation_ID + "'";
								data1[3] = "delete from Elitetask Where Objective_Guid = '" + old_Relation_ID + "'";
								data1[4] = "update  TABCCONSULTWORKORDER set  r_Arriveddate='" + Arriveddate + "',r_handlername='" + handlername + "',handlerphnoe='" + handlerphone + "',r_workingday=datediff( day, '" + starttime + "', '" + finishtime + "' ),r_starttime='" + starttime + "',r_finishtime='" + finishtime + "',handledescription='" + handledescription + "',workorder_state = 4 where RELATION_ID='" + old_Relation_ID + "'";
								log.debug("判断处理工单状态进行下一步处理SQL:" + data1.toString());
								int[] dataresult1 = eliteBean.updateBatch(data1, dataSourceID);
								log.debug("判断处理工单状态进行下一步处理SQL结果:" + dataresult1.toString());
								
								 if(business_source=='CD38FF'){//智慧化网格
									String json1="{\"sys_source\":\"WGH\",\"workorderid\":\""+workorderid+"\",\"sys_flag\":\"1\"}";
									Map<String, String> headMap = new HashMap<String, String>();
									headMap.put("Content-Type", "application/json");
									
									def objid;
									def sysurl;
									//判断是否属历史案件
									def objectiveresult = eliteBean.chaxun_sql("select objective_guid as objid from objective where createddate<='2022-02-28 21:00:00.00' and map_id='MYI3EW' and workorderid='" + workorderid + "' and Objective_Guid ='" + old_Handleby_ID + "'", "dataSource");
									if (objectiveresult.size() > 0) {
										objid = objectiveresult.get(0).get("objid");
										log.debug("objid:	" + objid);
										sysurl = "http://127.0.0.1:8080/EliteGeneralHttpTask/GeneralService/BP_WG_apiUnderdelivery";
									}else{
										sysurl = "http://127.0.0.1:8080/EliteGeneralHttpTask/GeneralService/BP_Zhsw_apiUnderdelivery";
									}
									
									injson=Util.doHttpPostUseHead(sysurl,json1,"UTF-8",100000,0,headMap);
								}
								if(business_source=='9999B1'){//数字化城管
									String json1="{\"sys_source\":\"CG\",\"workorderid\":\""+workorderid+"\",\"sys_flag\":\"1\"}";
									Map<String, String> headMap = new HashMap<String, String>();
									headMap.put("Content-Type", "application/json");
									def sysurl = "http://127.0.0.1:8080/EliteGeneralHttpTask/GeneralService/BP_CG_apiUnderdelivery";
									injson=Util.doHttpPostUseHead(sysurl,json1,"UTF-8",100000,0,headMap);
								} 
								//解析
								log.debug("调用返回信息：" + injson.toString());
								JSONObject inObject = new JSONObject(injson);
								String resultcode = GetJV(inObject, "resultcode");
								log.debug("resultcode：	" + resultcode);
								
								if(resultcode.equals("1")) {
									status=1;
								}else {
									status=0;
								}
								
							}
							
							//客服热线A13ACC  微信群DBCA45  报障小链接3E98AF 回访发送短信sql
							if(business_source=='A13ACC'||business_source=='DBCA45'||business_source=='3E98AF'){
								eliteBean.update("Insert Into Documentout (Documentout_Guid,documentfrom,Doctype,Status,Trialcount,Trialcountlimit,Documentpath,Handleby_Id,Handlegroup_Id,Customer_Guid,Createdby,Createddate,Expectedstartdate,Documentto,model_id,model_1,model_2,model_3,model_4) select NEWID(),2,3,0,0,5,dl.DOCUMENTPATH,'SELITE','SYSTEM',c.customer_guid,'SELITE',GETDATE(),GETDATE(),case when t.phone_number='' then c.mobile else t.phone_number end,case when t.business_source='A13ACC' then '680766' when t.business_source='DBCA45' then '680768' else '' end,c.customername,c1.Code_Name,c2.callnaturegroupdescription,c3.callnaturedescription from objective o LEFT JOIN TABCCONSULTWORKORDER t on o.objective_guid=t.RELATION_ID LEFT JOIN customer c on c.customer_guid=o.customer_guid LEFT JOIN c_codetables c1 on c1.code_id=t.administrative and c1.Use_Type='行政区域'  and c1.Use_Status=1  LEFT JOIN callnaturegroup c2 on c2.callnaturegroup_id=t.business_type_1  LEFT JOIN callnature c3 on c3.callnature_id=t.business_type_2  LEFT JOIN doctemplate dl on case when t.business_source='A13ACC' then '680766' when t.business_source='DBCA45' then '680768' else '' end=dl.doctemplate_id where 1=1 and dl.DOCUMENTPATH is not null and o.objective_guid='" + old_Relation_ID + "'","dataSource");
							}
							//智慧化网格CD38FF  数字化城管9999B1  插入回访第三方任务sql
							if(business_source=='CD38FF'||business_source=='9999B1'){
								eliteBean.update("insert into BP_workordertask(workorderguid,business_source,workorderid,objective_guid,status,createtime,modifytime,reqcount,resparameter) VALUES(NEWID(),'" + business_source + "','" + workorderid + "','" + old_Relation_ID + "','"+status+"',GETDATE(),GETDATE(),1,'" + injson + "')","dataSource");
							}
							dealMessage="当前处理状态反馈处理成功";
						} else {
							long endTime = System.currentTimeMillis();
							dealResult = "0";
							dealMessage = "当前处理结果变更的工单在CRM系统不存在ID或工单步骤不在处理节点";
							log.warn(dealMessage + ":" + workorderid);
						}
						dealResult = "1";
					} catch (Exception e) {
						dealResult = "0";
						dealMessage = "当前处理状态变更的工单整体处理SQL异常";
						log.error(dealMessage + ":" + e.getMessage());
					}


				}

				dealMap.put(workorderid, dealResult);
				dealMsgMap.put(workorderid, dealMessage);
			}
			// 将每条处理结果转换为JSONArray
			int j = 0;
			for (Map.Entry<String, String> m : dealMap.entrySet()) {
				JSONObject resObject = new JSONObject();
				resObject.put("id", m.getKey());
				resObject.put("code", m.getValue());
				resObject.put("message", dealMsgMap.get(m.getKey()).toString());
				resArray.put(j, resObject);
				j++;
			}
			log.debug(resArray.toString());
			long endTime = System.currentTimeMillis();
			// 包装拼接返回JSONObject
			reJson = "{\"resultcode\":\"1\",\"resultmessage\":\"处理完成、调用问题处理时长(毫秒):" + (endTime - startTime) + "\",\"data\":" + resArray.toString() + "}";

		} catch (JSONException e) {
			long endTime = System.currentTimeMillis();
			reJson = "{\"resultcode\":\"0\",\"resultmessage\":\"处理失败(" + e.getMessage() + "),调用问题处理时长(毫秒):" + (endTime - startTime) + "\",\"data\":[]}";
		}

		return reJson;
	}


	// 解析Json值
	public static String GetJV(JSONObject inJson, String getKey) {
		String Rev_Value = null;
		try {
			Rev_Value = inJson.getString(getKey);
		} catch (Exception e) {
			try {
				Rev_Value = String.valueOf(inJson.getInt(getKey));
			} catch (Exception e1) {
				try {
					Rev_Value = String.valueOf(inJson.getJSONArray(getKey));
				} catch (Exception e2) {
					try {
						Rev_Value = String.valueOf(inJson.getJSONObject(getKey));
					} catch (Exception e3) {
						Rev_Value = "";
					}
				}
			}
		} finally {
			if (Rev_Value == null || Rev_Value.equals("null") || Rev_Value.length() <= 0) {
				Rev_Value = "";
			} else {
			}
		}
		log.debug("解析-k=" + getKey + " v=" + Rev_Value);
		return Rev_Value;
	}

	// 非空校验isNull
	public static boolean isNull(String value) {

		boolean reFlag = true;
		if (value == "" || value.length() <= 0) {
			reFlag = true;
		} else {
			reFlag = false;
		}

		return reFlag;
	}

	// 非空校验isNullMSG
	public static String isNullMSG(String key, String value) {

		String reResult = "";
		if (value == "" || value.length() <= 0) {
			reResult = key + "必填字段;";
		}
		return reResult;
	}

}